package com.chisheng.caa.validator;

import com.chisheng.caa.util.MathUtil;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 注解 @Contains 的处理器
 */
@Component
public class ContainsValidator implements ConstraintValidator<Contains, Object>, BeanFactoryAware {

    /**
     * Spring 实例工厂
     */
    private BeanFactory beanFactory;

    /**
     * 有效取值集合
     */
    private List<Collection<?>> valuesList;

    @Override
    public void initialize(Contains annotation) {
        Class<?>[] beanClasses = annotation.beanClass();
        String[] beanNames = annotation.beanName();
        String[] methodNames = annotation.methodName();

        int length = MathUtil.min(beanNames.length, beanNames.length, methodNames.length);
        List<Collection<?>> valuesList = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            valuesList.add(executeValidMethod(beanClasses[i], beanNames[i], methodNames[i]));
        }

        this.valuesList = valuesList;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return value == null || isInAnyCollection(value);
    }

    @Override
    public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @SneakyThrows
    private Collection<?> executeValidMethod(Class<?> beanClass, String beanName, String methodName) {
        Object bean;
        if (!beanClass.equals(Void.class) && !"".equals(beanName)) {
            bean = beanFactory.getBean(beanName, beanClass);
        } else if (!beanClass.equals(Void.class)) {
            bean = beanFactory.getBean(beanClass);
        } else if (!"".equals(beanName)) {
            bean = beanFactory.getBean(beanName);
        } else {
            throw new IllegalArgumentException("未能正确指定 beanName 或 beanClass 参数");
        }

        Method method;
        if ("".equals(methodName)) {
            Method[] methods = bean.getClass().getDeclaredMethods();
            if (methods.length > 1) {
                throw new IllegalArgumentException(String.format("%s 中存在多个方法", beanClass));
            }

            method = methods[0];
        } else {
            method = bean.getClass().getDeclaredMethod(methodName);
        }

        method.setAccessible(true);
        return (Collection<?>) method.invoke(bean);
    }

    private boolean isInAnyCollection(Object value) {
        return valuesList.stream().anyMatch(e -> e.contains(value));
    }

}
